from api import Api
from ui_node import UiNode
import time
import threading
import random


def open_dy(api: Api):
    """
    打开抖音
    """
    packageName = "com.ss.android.ugc.aweme"
    activityName = "com.ss.android.ugc.aweme.main.MainActivity"
    note = "打开抖音"
    api.start_app(package_name=packageName, activity_name=activityName, note=note)


def next_vedio(api: Api):
    """
    刷下一个视频
    """
    api.swipe(500, 1500, 500, 500, 150, "观看下一个视频")


def start_job(device_no):
    # 初始化
    api = Api("http://121.37.213.206:8881", device_no=device_no)
    # 打开抖音
    open_dy(api)

    # 休眠5妙
    time.sleep(5)

    while True:
        next_vedio(api)
        # 休眠5妙
        time.sleep(5)
        if random.Random().randint(1, 10) > 5:
            # 获取ui xml
            xml = api.get_uixml('获取ui xml')
            if xml == "":
                continue

            # 解析xml
            node = UiNode.from_xml(xml)
            # 查找点赞节点
            dianzans = node.list_by_contain_desc("点赞")
            if len(dianzans):
                # 点击点赞
                dianzan = dianzans[0]
                api.click(dianzan.bounds.center_x, dianzan.bounds.center_y)


if __name__ == "__main__":

    '''批量控制手机,自动观看抖音,并随机点赞'''

    # 创建线程列表
    threads = []
    # 设备列表
    device_nos = ["931292"]
    # 每个设备启动一个单独线程执行任务
    for device_no in device_nos:
        t = threading.Thread(target=start_job, args=[device_no])
        t.start()
        threads.append(t)

    # 等待任务执行完成
    for t in threads:
        t.join()

    print("所有任务n已完成")
